const express = require('express')
const pdfParse = require('pdf-parse')
const fs = require('fs')
const db = require('../db')
const { answer } = require('./interviewsController')
const app = express()
const axios = require('axios');

//上传公司详情文件
const upload = async (req, res) => {
    //校验文件是否上传
    if (!req.file) {
        return res.cc({
            code: 400,
            message: '请上传文件'
        })
    }

    //校验文件类型
    const mime = req.file.mimetype
    if (mime !== 'application/pdf') {
        return res.cc({
            code: 400,
            message: "只支持Pdf文件！"
        })
    }

    //解析文件内容
    let contentText = '';
    let companyName = ''
    let companyIntroduction = ''
    let position = ''
    let positionDesc = ''
    let fileName = ''
    let filePath = ''
    try {
        if (mime === "application/pdf") {
            console.log('req.file:', req.file)
            console.log('文件路径:', req.file.path)
            // 读取上传的PDF文件内容
            const dataBuffer = fs.readFileSync(req.file.path)
            // pdf-parse 库对 dataBuffer（二进制的 PDF 文件内容）进行解析，返回解析后的数据对象（包含文本内容等信息）
            const data = await pdfParse(dataBuffer)
            contentText = data.text
            //提取公司名字
            const match = contentText.match(/公司名称[:：\s]*([^\s，。；,;.\n\r]+(有限公司|公司))/)
            companyName = match ? match[1] : ''
            //提取公司简介
            const companyMatch = contentText.match(/公司简介：(.*?)(?:\n\S+：|$)/s)
            companyIntroduction = companyMatch ? companyMatch[1] : ''
            //提取岗位
            const positionMatch = contentText.match(/招聘岗位：(.*?)(?:\n\S+：|$)/s)
            position = positionMatch ? positionMatch[1] : ''
            //提取岗位描述
            const PosidescMatch = contentText.match(/岗位描述：(.*?)(?:\n\S+：|$)/s)
            positionDesc = PosidescMatch ? PosidescMatch[1] : ''
            //文件名
            fileName = req.file.filename
            //文件路径
            filePath = req.file.path
        }
    } catch (err) {
        return res.cc({
            code: 500,
            message: "文件解析失败！"
        })
    }

    // 将解析后的数据存入数据库当中
    const fileSql = 'INSERT INTO CompanyDocuments (user_id, company_name, company_desc, position, file_name, file_path, content_text, document_type) VALUES (?,?,?,?,?,?,?,?)'
    const { user_id } = req.body
    if (!user_id) {
        return res.cc({
            code: 400,
            message: '用户ID不能为空'
        });
    }

    await db.query(fileSql, [user_id, companyName, companyIntroduction, position, fileName, filePath, positionDesc, mime])

    return res.send({
        code: 200,
        message: '文件上传并解析成功！'
    })
}

// 调用AI服务解析简历
const parseResumeWithAI = async (resumeContent) => {
    try {
        const response = await axios.post('http://hzc319820.cn:1921/api/chat', {
            model: "interviewer-agent",
            messages: [
                {
                    role: "user",
                    content: resumeContent
                }
            ],
            stream: false,
            options: {
                temperature: 0.7,
                top_p: 0.9,
                num_predict: 1024
            }
        });

        // 先打印原始返回数据
        console.log('AI服务原始返回:', response.data);
        console.log('message.content:', response.data.message.content);

        if (!response.data.message.content) {
            return {
                success: false,
                error: 'AI服务返回内容为空'
            };
        }

        // 尝试解析JSON，如果失败则返回原始文本
        let aiResponse;
        try {
            aiResponse = JSON.parse(response.data.message.content);
        } catch (parseError) {
            console.log('JSON解析失败，返回原始文本');
            aiResponse = {
                raw_content: response.data.message.content
            };
        }

        return {
            success: true,
            data: aiResponse
        };
    } catch (error) {
        console.error('AI服务调用失败:', error);
        return {
            success: false,
            error: error.message
        };
    }
};

//上传个人简历
const uploadResume = async (req, res) => {
    try {
        //校验文件是否上传
        if (!req.file) {
            return res.cc({
                code: 400,
                message: '请上传个人简历！'
            })
        }

        const { user_id } = req.body;
        //校验文件类型
        const mime = req.file.mimetype

        if (!user_id) {
            return res.cc({
                code: 400,
                message: '用户ID不能为空'
            });
        }

        let resumeContent = '';
        if (req.file.mimetype === 'application/pdf') {
            const dataBuffer = fs.readFileSync(req.file.path)
            const data = await pdfParse(dataBuffer)
            resumeContent = data.text
            console.log(resumeContent);
        }

        //3.调用ai服务解析简历
        const aiResult = await parseResumeWithAI(resumeContent)
        console.log("ai服务解析", aiResult);

        if (!aiResult.success) {
            return res.cc({
                code: 500,
                message: 'ai解析失败',
                data: aiResult
            })
        }

        const filePath = req.file.path

        //插入数据库
        await db.query(
            'UPDATE Users SET resume_path = ? WHERE id = ?',
            [filePath, user_id]
        )
        console.log(filePath)

        return res.send({
            code: 200,
            message: '简历上传成功',
            data: {
                filePath,
            }
        })
    } catch (err) {
        console.error("上传失败", err);
        return res.cc({
            code: 500,
            message: '上传失败' + err.message
        })
    }
}

module.exports = {
    upload,
    uploadResume,
}